//
//  DCTabbarController.m
//  DCProject
//
//  Created by bigbing on 2019/4/1.
//  Copyright © 2019 bigbing. All rights reserved.
//

#import "DCTabbarController.h"
#import "DCUpdateTool.h"
#import "QKTabBar.h"
#import "YNSHomeController.h"
#import "YNSMineController.h"
#import "YNSNewsViewController.h"
//#import "DHHomeVC.h"
//#import "DHClassVC.h"
//#import "DHShopCartVC.h"
//#import "DHMyVC.h"
//#import "DHOrderVC.h"

#define ControllerClassKey @"controllerClassKey"
#define TitleNameKey @"titleNameKey"
#define ImgNormalKey @"imgNormalKey"
#define ImgSelectKey @"imgSelectKey"

@interface DCTabbarController () <UITabBarControllerDelegate>

@property(nonatomic,strong) QKTabBar * qKTabbar;
@property(nonatomic,strong) YNSHomeController * homeVC;
@property(nonatomic,strong) YNSNewsViewController * newsVC;
@property(nonatomic,strong) YNSMineController * mineVC;
//@property(nonatomic,strong) DHClassVC * classVC;
//@property(nonatomic,strong) DHShopCartVC * shopCartVC;
//@property(nonatomic,strong) DHMyVC * myVC;

@end

@implementation DCTabbarController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    self.fd_prefersNavigationBarHidden = YES;
    
    self.delegate = self;
    
    NSArray * array = @[@{
                            ControllerClassKey:@"YNSHomeController",
                            TitleNameKey:@"群聊",
                            ImgNormalKey:@"home_normal",
                            ImgSelectKey:@"home_select"},
                        @{
                            ControllerClassKey:@"YNSNewsViewController",
                            TitleNameKey:@"资讯",
                            ImgNormalKey:@"new_normal",
                            ImgSelectKey:@"news_select"},
                        @{
                            ControllerClassKey:@"YNSMineController",
                            TitleNameKey:@"我的",
                            ImgNormalKey:@"mine_normal",
                            ImgSelectKey:@"mine_select"},
                      
                    
                        
    ];
    __weak typeof(self) weakself = self;
    [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        UIViewController * vc = [NSClassFromString(obj[ControllerClassKey]) new];
        vc.tabBarItem.title = obj[TitleNameKey];
        vc.tabBarItem.tag = idx;
        vc.tabBarItem.image = [[UIImage imageNamed:obj[ImgNormalKey]] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        vc.tabBarItem.selectedImage = [[UIImage imageNamed:obj[ImgSelectKey]] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        [weakself addChildViewController:vc];
        
        if (idx == 0) {
            self.homeVC = (YNSHomeController *)vc;
        }else if (idx == 1){
            self.newsVC = (YNSNewsViewController *)vc;
        }else if (idx == 2){
            self.mineVC = (YNSMineController *)vc;
        }
    }];
    
    
    
    [self initAppearance];
//    [self setCustomtabbar];
    
    
    //注册登录状态监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tabbarSwitch:) name:DC_NotificationName_TabbarSwitch object:nil];
    
    [self requestNewVersion];//请求最新版本
    [self dc_startLocation];//请求位置
}

#pragma mark - 设置自定义中心按钮
- (void)setCustomtabbar{
    self.qKTabbar = [[QKTabBar alloc]init];
    [self setValue:self.qKTabbar forKeyPath:@"tabBar"];
    [self.qKTabbar.centerBtn addTarget:self action:@selector(centerBtnClick:) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - 自定义中心按钮相应方法
- (void)centerBtnClick:(UIButton *)btn{
    //    self.selectedViewController = _release;
    
}

#pragma mark --- 配置框架结构
- (void)initAppearance
{
    // 设置TabBar样式
    if (@available(iOS 13.0, *)) {
        UITabBarAppearance *appearance = [[UITabBarAppearance alloc] init];
        appearance.shadowColor = [UIColor dc_colorWithHexString:DC_EEEEEE];
        appearance.backgroundColor = [UIColor whiteColor];
        appearance.shadowImage = [self imageWithColor:[UIColor dc_colorWithHexString:DC_EEEEEE] size:CGSizeMake(kScreenW, 1)];
        // 设置未被选中的颜色
        appearance.stackedLayoutAppearance.normal.titleTextAttributes = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor dc_colorWithHexString:DC_999999],NSForegroundColorAttributeName,PFRFont(12),NSFontAttributeName, nil];
        // 设置被选中时的颜色
        appearance.stackedLayoutAppearance.selected.titleTextAttributes = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor dc_colorWithHexString:DC_ThemeColor],NSForegroundColorAttributeName,PFRFont(12),NSFontAttributeName, nil];
        [self.tabBar setStandardAppearance:appearance];
    }else{
        [[UITabBar appearance] setTranslucent:NO];
        [[UITabBar appearance] setBarTintColor:[UIColor whiteColor]];
        [[UITabBar appearance] setShadowImage:[self imageWithColor:[UIColor dc_colorWithHexString:DC_EEEEEE] size:CGSizeMake(kScreenW, 1)]];
        [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor dc_colorWithHexString:DC_999999],NSForegroundColorAttributeName,PFRFont(12),NSFontAttributeName, nil] forState:0];
        [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor dc_colorWithHexString:DC_ThemeColor],NSForegroundColorAttributeName,PFRFont(12),NSFontAttributeName, nil] forState:UIControlStateSelected];
    }
    [self setupBarButtonItemTheme];
}

/**
 *  设置UIBarButtonItem的主题
 */
-(void)setupBarButtonItemTheme {
    //通过设置 appearance对象，能够修改整个项目中所有UIBarButtonItem的样式
    UIBarButtonItem *appearance = [UIBarButtonItem appearance];
    
    //设置文字的属性
    //1.设置普通状态下文字的属性
    NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
    //设置字体
    textAttrs[NSFontAttributeName] = [UIFont systemFontOfSize:15.0];
    
    //设置颜色为橙色
    textAttrs[NSForegroundColorAttributeName] = [UIColor dc_colorWithHexString:@"#131217"];
    [appearance setTitleTextAttributes:textAttrs forState:UIControlStateNormal];

    //2.设置高亮状态下文字的属性
    NSMutableDictionary *hightextAttrs = [NSMutableDictionary dictionaryWithDictionary:textAttrs];
    //设置颜色为红色
    hightextAttrs[NSForegroundColorAttributeName] = [UIColor dc_colorWithHexString:@"#131217"];
    [appearance setTitleTextAttributes:hightextAttrs forState:UIControlStateHighlighted];

    //3.设置不可用状态下文字的属性
    NSMutableDictionary *disabletextAttrs = [NSMutableDictionary dictionaryWithDictionary:textAttrs];
    disabletextAttrs[NSForegroundColorAttributeName] = [UIColor dc_colorWithHexString:@"#131217"];
    [appearance setTitleTextAttributes:disabletextAttrs forState:UIControlStateDisabled];
}


- (void)tabbarSwitch:(NSNotification *)notification
{
    [self.navigationController popToRootViewControllerAnimated:NO];
    
    NSInteger idx = [notification.userInfo[@"tabbar"] integerValue];
    self.selectedIndex = idx;
    
//    NSString * goStr = notification.userInfo[@"go"];
//    if (goStr && goStr.length > 0) {
//        if ([goStr isEqualToString:@"orderList"]) {
//            [self.navigationController pushViewController:[DHOrderVC new] animated:YES];
//        }
//    }
}

#pragma mark - <UITabBarControllerDelegate>
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{
    // 控制器跳转拦截
    if(viewController == [tabBarController.viewControllers objectAtIndex:1] || viewController == [tabBarController.viewControllers objectAtIndex:2]){
        //        if (![[DCLoginTool shareTool] dc_isLogin]) {
        //            [[DCLoginTool shareTool] dc_pushLoginControllerSuccessBlock:^{
        //
        //            }];
        //            return NO;
        //        }
    }
    return YES;
}



- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{
    [self tabBarButtonClick:[self getTabBarButton]];
}


- (UIControl *)getTabBarButton
{
    NSMutableArray *tabBarButtons = [[NSMutableArray alloc]initWithCapacity:0];
    
    for (UIView *tabBarButton in self.tabBar.subviews) {
        if ([tabBarButton isKindOfClass:NSClassFromString(@"UITabBarButton")]){
            [tabBarButtons addObject:tabBarButton];
        }
    }
    UIControl *tabBarButton = [tabBarButtons objectAtIndex:self.selectedIndex];
    
    return tabBarButton;
}

#pragma mark - 点击动画
- (void)tabBarButtonClick:(UIControl *)tabBarButton
{
    for (UIView *imageView in tabBarButton.subviews) {
        if ([imageView isKindOfClass:NSClassFromString(@"UITabBarSwappableImageView")]) {
            //需要实现的帧动画,这里根据自己需求改动
            CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
            animation.keyPath = @"transform.scale";
            animation.values = @[@1.0,@1.1,@0.9,@1.0];
            animation.duration = 0.3;
            animation.calculationMode = kCAAnimationCubic;
            //添加动画
            [imageView.layer addAnimation:animation forKey:nil];
        }
    }
}

#pragma mark - 禁止屏幕旋转
- (BOOL)shouldAutorotate
{
    return NO;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;//只支持这一个方向(正常的方向)
}


#pragma mark - 请求 获取最新版本
- (void)requestNewVersion
{
    //    [DCObjectManager dc_removeUserDataForkey:DC_IsAuditVersion_Key];
    //    [DC_KeyWindow dc_disable];
    //    [[DCAPIManager shareManager] dc_getAppVersionWithSuccess:^(id response) {
    //        [DC_KeyWindow dc_enable];
    //
    //        if (response && [response isKindOfClass:[NSDictionary class]]) {
    //
    //            NSDictionary * dict = response;
    //            NSString * version = dict[@"version"]; // 线上版本
    //            if (version && [version length] > 0) {
    //                NSString * app_verson = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    //                if ( [[DCUpdateTool shareClient] dc_isUpdateWithVersion:version onlineVer:app_verson]) {
    //                    [DCObjectManager dc_saveUserData:@"1111" forKey:DC_IsAuditVersion_Key];
    //                }
    //            }
    //
    //        } else { // 未上线
    //            [DCObjectManager dc_saveUserData:@"1111" forKey:DC_IsAuditVersion_Key];
    //        }
    //
    //    } failture:^(NSError *error) {
    //        [DC_KeyWindow dc_disable];
    //    }];
}

#pragma mark - 定位
- (void)dc_startLocation
{
    WEAKSELF;
    //    [[DCLocationManager shareManager] dc_location];
    //    [[DCLocationManager shareManager] setSuccessBlock:^(NSString *title) {
    //
    //        if ([DCObjectManager dc_readUserDataForKey:DC_CurrentCity_Key]) {
    //            NSString * currentCity = [DCObjectManager dc_readUserDataForKey:DC_CurrentCity_Key];
    //            if (![title containsString:currentCity]) { // 两个值不相等
    //
    //                BOOL hasShow = NO;
    //                for (id class in DC_KeyWindow.subviews) {
    //                    if ([class isKindOfClass:[DCAlterView class]]) {
    //                        hasShow = YES;
    //                    }
    //                }
    //
    //                if (hasShow == NO) {
    //
    //                    DCAlterView * alterView = [[DCAlterView alloc] initWithTitle:@"提示" content:[NSString stringWithFormat:@"当前定位为%@,是否切换到%@",title,title]];
    //                    [alterView addActionWithTitle:@"取消" type:DCAlterTypeCancel halderBlock:nil];
    //                    [alterView addActionWithTitle:@"确认" type:DCAlterTypeDone halderBlock:^(UIButton *button) {
    //                        [weakSelf.homeVC dc_cityName:title];
    //                    }];
    //
    //                    [DC_KeyWindow addSubview:alterView];
    //                    [alterView mas_makeConstraints:^(MASConstraintMaker *make) {
    //                        make.edges.equalTo(DC_KeyWindow);
    //                    }];
    //                }
    //
    //            } else {
    //                [weakSelf.homeVC dc_cityName:title];
    //            }
    //        } else {
    //            [weakSelf.homeVC dc_cityName:title];
    //        }
    //    }];
}


-(UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size {
    if (!color || size.width <= 0 || size.height <= 0) return nil;
    CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}


@end
